package palms.locationsearch;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.LinkedList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import palms.location.results.ALocation;

/*
 *	Examplo:
 *	GooglePlacesSearch gps = new GooglePlacesSearch();
 *	gps.setLocation(38.736830, -9.138181);
 *	gps.setTypes("food"); 
 *	e depois sacar a lista... 
 * 
 */

public class GooglePlacesSearch {

	private String url;			//https://maps.googleapis.com/maps/api/place/search/
	private String output;		//xml?
	private String key;			//key=AIzaSyC2T02x40y4FXERyAZwqDF9gEuB9xiuRL4
	private String location; 	//location=-33.8670522,151.1957362
	private String radius;		//radius=500		->in meters
	private String types;		//types=food
	private String sensor;		//sensor=true or false 	->indicates if query comes from GPS device
	
	public GooglePlacesSearch(){
		this.url = "https://maps.googleapis.com/maps/api/place/search/";
		this.output = "xml?";
		this.key = "key=AIzaSyC2T02x40y4FXERyAZwqDF9gEuB9xiuRL4";
		this.radius = "radius=300";
		this.sensor = "sensor=true";
	}
	
	public void setLocation(double lat, double log){
		this.location = "location=" + lat + "," + log;
	}
	
	public void setTypes(String t){
		this.types = "types=" + t;
	}
	
	public String getURL(){
		return url + output + location + "&" + radius + "&" + types + "&" + sensor + "&" + key;
	}
	
	public LinkedList<ALocation> getResults(){

		LinkedList<ALocation> res = new LinkedList<ALocation>();
		
		try {
			
			//InputStream is = new URL(this.getURL()).openStream();
			//String content = readInputStreamAsString(is);
			//System.out.println(content);
			
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(this.getURL());
			
			
			NodeList nList = doc.getElementsByTagName("result");

			for (int temp = 0; temp < nList.getLength(); temp++) {

				Node nNode = nList.item(temp);
				Element eElement = (Element) nNode;
				//System.out.println("Name : " + getTagValue("name", eElement));
				//System.out.println("-lat : " + getTagValue("lat", eElement));
				//System.out.println("-lng : " + getTagValue("lng", eElement));
				//System.out.println("-address : " + getTagValue("vicinity", eElement));

				ALocation al = new ALocation();
				al.setName(getTagValue("name", eElement));
				al.setLat(new Double(getTagValue("lat", eElement)));
				al.setLog(new Double(getTagValue("lng", eElement)));
				al.setAddress(getTagValue("vicinity", eElement));
				al.setImgUrl(getTagValue("icon", eElement));
				
				res.add(al);
				
			}

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return res;
		
	}
	
	private static String getTagValue(String sTag, Element eElement) {
		NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
	 
	        Node nValue = (Node) nlList.item(0);
	 
		return nValue.getNodeValue();
	  }
	
	public static String readInputStreamAsString(InputStream in) throws IOException {

		BufferedInputStream bis = new BufferedInputStream(in);
		ByteArrayOutputStream buf = new ByteArrayOutputStream();
		int result = bis.read();
		while(result != -1) {
			byte b = (byte)result;
			buf.write(b);
			result = bis.read();
		}        
		return buf.toString();
	}
	
}

/*Supporting types
accounting
airport
amusement_park
aquarium
art_gallery
atm
bakery
bank
bar
beauty_salon
bicycle_store
book_store
bowling_alley
bus_station
cafe
campground
car_dealer
car_rental
car_repair
car_wash
casino
cemetery
church
city_hall
clothing_store
convenience_store
courthouse
dentist
department_store
doctor
electrician
electronics_store
embassy
establishment
finance
fire_station
florist
food
funeral_home
furniture_store
gas_station
general_contractor
geocode
grocery_or_supermarket
gym
hair_care
hardware_store
health
hindu_temple
home_goods_store
hospital
insurance_agency
jewelry_store
laundry
lawyer
library
liquor_store
local_government_office
locksmith
lodging
meal_delivery
meal_takeaway
mosque
movie_rental
movie_theater
moving_company
museum
night_club
painter
park
parking
pet_store
pharmacy
physiotherapist
place_of_worship
plumber
police
post_office
real_estate_agency
restaurant
roofing_contractor
rv_park
school
shoe_store
shopping_mall
spa
stadium
storage
store
subway_station
synagogue
taxi_stand
train_station
travel_agency
university
veterinary_care
zoo
*/